package ca.tatham.senssim.diffusion;

import java.util.HashMap;
import java.util.Map;

import ca.tatham.senssim.Simulation;
import ca.tatham.senssim.diffusion.InterestMessage.Interest;
import ca.tatham.senssim.util.Address;

public class SinkNodeDirectedDiffusion extends AbstractSinkNode
{
  private final static Interest EXPLORATORY = new Interest(SENSOR_TYPE,
      60 * 1000, 60 * 1000 * 2, REGION);
  private final static Interest REINFORCEMENT = new Interest(SENSOR_TYPE,
      1 * 1000, 60 * 1000 * 5, REGION);

  private final Map<Address, Integer> m_reinforcedSentTime = new HashMap<Address, Integer>();

  protected SinkNodeDirectedDiffusion(Address address)
  {
    super(address);
  }

  @Override
  protected void processDataMessage(DataMessage packet)
  {
    if (saveData(packet))
    {
      sendReinforcment(packet.getSource());
    }
  }

  @Override
  protected void sendPeriodicInterest()
  {
    sendPacket(new InterestMessage(getAddress(), Address.BROADCAST, EXPLORATORY));
  }

  private void sendReinforcment(Address to)
  {
    Integer lastSent = m_reinforcedSentTime.get(to);
    int now = Simulation.getTime();
    if (lastSent == null || now > lastSent + 10000)
    {
      m_reinforcedSentTime.put(to, now);
      sendPacket(new InterestMessage(getAddress(), to, REINFORCEMENT));
      log("reinforcing last path from " + to);
    }
  }

}
